import 'package:flutter/material.dart' hide TabBar;
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_widgets/config/kq_global.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';
import 'package:kq_flutter_core_widget/widgets/tabBar/kq_tabs.dart';

import '../divider/kq_divider.dart';
import '../tagView/kq_number_tag_view.dart';
import 'kq_number_tab.dart';

/// 指示器类型
enum IndicatorType {
  ///下划线
  underline,

  ///圆形背景
  roundBg
}

/// 通用 TabBar
///
/// @author 周卓
///
class KqTabBar extends StatefulWidget {
  /// 指示器类型，0：下划线，1：圆形背景
  final IndicatorType indicatorType;

  /// 支持器大小
  final TabBarIndicatorSize? indicatorSize;

  /// TabController
  final TabController? tabController;

  /// Tab数据，包括标题和角标，以及是否显示角标
  final List<TabDataEntity> items;

  /// 自定义TabBar右侧控件，比如管理Tab的菜单
  final Widget? customTabRightView;

  /// 是否可水平滚动，否则均分
  final bool scrollable;

  /// Tab切换回调
  final ValueChanged<int>? onTap;

  /// 文字颜色和下划线颜色处理器，下划线颜色跟随选中的文字颜色，如果不设置，默认使用[_KqTabBarState._defaultTextColorBuilder]
  final Color? Function(IndicatorType indicatorType, bool selected)?
      textColorBuilder;

  /// 字体大小处理器，如果不设置，默认使用[_KqTabBarState._defaultFontSizeBuilder]
  final double Function(IndicatorType indicatorType, bool selected)?
      fontSizeBuilder;

  /// Tab背景颜色，针对 [IndicatorType.roundBg] 类型，选中时的颜色，默认跟随主题亮色
  final Color? roundBgColor;

  /// 角标最大数字，超过显示"[tagMaxNumber]+"，默认99
  final int tagMaxNumber;

  /// 是否隐藏底部分割线
  final bool hideDivider;

  /// 底部分割线颜色
  final Color? dividerColor;

  /// 默认选中位置，默认0，仅在[tabController]没传时生效
  final int initialIndex;

  /// 背景颜色
  final Color? backgroundColor;

  const KqTabBar(
      {Key? key,
      required this.items,
      this.tabController,
      this.indicatorType = IndicatorType.underline,
      this.indicatorSize,
      this.textColorBuilder,
      this.customTabRightView,
      this.fontSizeBuilder,
      this.tagMaxNumber = 99,
      this.initialIndex = 0,
      this.roundBgColor,
      this.backgroundColor,
      this.scrollable = false,
      this.hideDivider = false,
      this.dividerColor,
      this.onTap})
      : super(key: key);

  @override
  _KqTabBarState createState() => _KqTabBarState();
}

class _KqTabBarState extends State<KqTabBar> with TickerProviderStateMixin {
  /// 默认字体大小处理器
  double _defaultFontSizeBuilder(IndicatorType indicatorType, bool selected) {
    if (indicatorType == IndicatorType.underline) {
      //underline
      return 14.sp;
    } else {
      //roundBg
      return 12.sp;
    }
  }

  /// 默认文字和下划线颜色处理器
  Color _defaultTextColorBuilder(IndicatorType indicatorType, bool selected) {
    if (indicatorType == IndicatorType.underline) {
      //underline
      return selected
          ? (KqThemeManager.instance.getConfig().commonConfig.mainColor ??
              KqThemeColors.bgBlue)
          : KqThemeColors.text26;
    } else {
      //roundBg
      return selected ? KqThemeColors.textWhite : KqThemeColors.text26;
    }
  }

  @override
  Widget build(BuildContext context) {
    TabBarIndicatorSize indicatorSize = widget.indicatorSize ??
        (widget.indicatorType == IndicatorType.underline
            ? TabBarIndicatorSize.tab
            : TabBarIndicatorSize.label);
    return Column(
      children: [
        Container(
          color: widget.backgroundColor ?? Colors.white,
          child: Row(
            children: [
              Expanded(
                  child: Container(
                      height: 40.r,
                      padding: EdgeInsets.symmetric(
                          vertical:
                              widget.indicatorType == IndicatorType.underline
                                  ? 0
                                  : 8.r,
                          horizontal:
                              widget.indicatorType == IndicatorType.underline
                                  ? 0
                                  : 4.r),
                      child: TabBar(
                          //选中的文字颜色
                          labelColor: _textColor(true),
                          //选中的文字样式
                          labelStyle: TextStyle(
                              color: _textColor(true),
                              fontSize: _fontSize(true)),
                          //未选中的文字颜色
                          unselectedLabelColor: _textColor(false),
                          //未选中的文字样式
                          unselectedLabelStyle: TextStyle(
                              color: _textColor(false),
                              fontSize: _fontSize(false)),
                          controller: widget.tabController ??
                              TabController(
                                  initialIndex: widget.initialIndex,
                                  length: widget.items.length,
                                  vsync: this),
                          isScrollable: widget.scrollable || KqGlobal.tabBarScrollable,
                          indicatorWeight:
                              widget.indicatorType == IndicatorType.underline
                                  ? 2.r
                                  : 0,
                          indicatorSize: indicatorSize,
                          indicatorPadding:
                              widget.indicatorType == IndicatorType.underline
                                  ? EdgeInsets.zero
                                  : EdgeInsets.symmetric(horizontal: -12.r),
                          labelPadding: EdgeInsets.symmetric(
                              horizontal: widget.scrollable || KqGlobal.tabBarScrollable ? 20.r : 16.r),
                          onTap: widget.onTap,
                          tabs: widget.items
                              .map((e) => KqNumberTab(
                                    text: e.title,
                                    top: widget.indicatorType ==
                                            IndicatorType.underline
                                        ? 4.r
                                        : -4.r,
                                    numberBuilder: () => e.hideNumber
                                        ? Container()
                                        : KqNumberTagView(
                                            number: e.number,
                                            minSize: 12.r,
                                            fontSize: 8.sp,
                                            backgroundColor: _tagBgColor(),
                                            max: widget.tagMaxNumber,
                                          ),
                                  ))
                              .toList(),
                          indicator: widget.indicatorType ==
                                  IndicatorType.underline
                              ? UnderlineTabIndicator(
                                  borderSide: BorderSide(
                                      width: 2.r,
                                      // 下划线颜色
                                      color: _underlineColor()),
                                )
                              : BoxDecoration(
                                  //圆形背景颜色
                                  color: _roundBgColor(),
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(30.r)))))),
              widget.customTabRightView == null
                  ? Container()
                  : widget.customTabRightView!
            ],
          ),
        ),
        if (!widget.hideDivider)
          KqDivider(color: widget.dividerColor ?? KqThemeColors.lineColor)
      ],
    );
  }

  /// 文字颜色
  _fontSize(bool selected) {
    return widget.fontSizeBuilder == null
        ? _defaultFontSizeBuilder(widget.indicatorType, selected)
        : widget.fontSizeBuilder!(widget.indicatorType, selected);
  }

  /// 文字颜色
  _textColor(bool selected) {
    return widget.textColorBuilder == null
        ? _defaultTextColorBuilder(widget.indicatorType, selected)
        : widget.textColorBuilder!(widget.indicatorType, selected);
  }

  /// 角标背景颜色
  _tagBgColor() {
    return widget.indicatorType == IndicatorType.underline
        ? _underlineColor()
        : _roundBgColor();
  }

  /// 圆背景颜色
  _roundBgColor() {
    return widget.roundBgColor ??
        (KqThemeManager.instance.getConfig().commonConfig.mainLightColor ??
            KqThemeColors.textLightBlue);
  }

  /// 下划线颜色
  _underlineColor() {
    return widget.textColorBuilder == null
        ? _defaultTextColorBuilder(IndicatorType.underline, true)
        : widget.textColorBuilder!(IndicatorType.underline, true);
  }
}

/// Tab数据填充
class TabDataEntity {
  /// 标题
  String title;

  /// 数字角标
  int number;

  /// 是否隐藏角标
  bool hideNumber;

  /// 额外数据，备用
  dynamic extraData;

  TabDataEntity(this.title,
      {this.number = 0, this.hideNumber = false, this.extraData});
}
